﻿#include "ScrollView.h"

float s_actionDuration = .1f;
float s_toleranceForMoving = 96;


bool ScrollView::init(const Size& size, const Size& innerSize)
{
	if (!NodeSnatch::init(this))
	{
		return false;
	}
	Size size2 = size;
	if (size2.equals(Size::ZERO))
	{
		size2 = cc::vsSize();
	}
	if (!NodeRect::init(Vec2(0, 0), size2))
	{
		return false;
	}
	NodeRect::setContentSize(size2);

	NodeRect::addChild(_innerNode = Node::create());
	if (!innerSize.equals(Size::ZERO))
	{
		size2 = innerSize;
	}
	_innerNode->setContentSize(size2);
	setDragType(eDrag::Both);
	return true;
}


void ScrollView::setContentSize(const Size& size)
{
	NodeRect::setContentSize(size);
	NodeRect::setRect(Vec2::ZERO, _contentSize);
}


void ScrollView::doDraging(const Vec2& worldSpace)
{
	Vec2 v = trimPosition(_innerNode->getPosition(), 0);
	if (!_isBounceable)
	{
		_innerNode->setPosition(v);
	}
	else if (!v.equals(_innerNode->getPosition()))
	{
		_innerNode->stopAllActions();
		_innerNode->runAction(MoveTo::create(s_actionDuration, v));
	}
}


Vec2 ScrollView::trimPosition(Vec2 v, float tolerance)
{
	const float &w = _contentSize.width;
	const float &h = _contentSize.height;

	Vec2 vs = _innerNode->getContentSize();
	float sw = vs.x;
	float sh = vs.y;
	vs += v;

	Vec2 v2 = v;
	bool f = false;
	if (v.x > tolerance)
	{
		f = true;
		v2.x = tolerance;
	}
	else if (vs.x + tolerance < w)
	{
		f = true;
		v2.x = w - sw - tolerance;
	}
	if (v.y > tolerance)
	{
		f = true;
		v2.y = tolerance;
	}
	else if (vs.y + tolerance < h)
	{
		v2.y = h - sh - tolerance;
	}
	return v2;
}





// void ScrollView::update(float delta)
// {
// 	if (!_isEndMoving)
// 	{
// 		return;
// 	}
// 	if (std::abs(_vecOffs.x) < 1 && std::abs(_vecOffs.y) < 1)
// 	{
// 		_isEndMoving = false;
// 		return;
// 	}
// 	_innerNode->setPosition(_innerNode->getPosition() + _vecOffs * delta);
// 	_innerNode->setPosition(trimPosition(_innerNode->getPosition(), 0));
// 	_vecOffs = _vecOffs * .96f;
// }





